<template>
  <div class="store-edit-new-container">
    <!-- 标签页切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane :label="props.storeId?'编辑门店信息':'新增门店信息'" name="info">
        <el-form :model="storeInfo" :rules="rules" ref="infoFormRef" label-width="120px">
          <el-form-item label="门店名称" prop="storeName">
            <el-input v-model="storeInfo.storeName" placeholder="请输入门店名称" />
          </el-form-item>

          <el-form-item label="门店类型" prop="storeType">
            <el-select v-model="storeInfo.storeType" placeholder="请选择门店类型">
              <el-option label="直营店" value="直营店" />
              <el-option label="加盟店" value="加盟店" />
            </el-select>
          </el-form-item>

          <el-form-item label="门店电话" prop="servicePhone">
            <el-input v-model="storeInfo.servicePhone" placeholder="请输入门店电话" />
          </el-form-item>

          <el-form-item label="营业状态" prop="businessStatus">
            <el-input v-model="storeInfo.businessStatus" placeholder="请输入营业状态" />
          </el-form-item>

          <el-form-item label="店长ID" prop="managerId">
            <el-input v-model="storeInfo.managerId" placeholder="请输入店长ID" />
          </el-form-item>

          <el-form-item label="门店工位数量" prop="stationCount" >
            <el-input-number  v-model="storeInfo.stationCount" placeholder="工位数量" />
          </el-form-item>

          <el-form-item label="营业时间" prop="businessHours">
            <el-input v-model="storeInfo.businessHours" placeholder="营业时间" />
            <el-button type="success" @click="newTime">新增营业时间</el-button>
          </el-form-item>

          <!-- 地址选择对话框 -->
          <el-dialog
              title="新增营业时间"
              v-model="timeDialogVisible" width="500px" :close-on-click-modal="false"
          >

            <el-time-picker
                v-model="storeInfo.businessHoursPeriod"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="开始时间"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="handleBusinessHoursChange">
            </el-time-picker>

            <!-- 对话框底部按钮 -->
            <div slot="footer" class="dialog-footer">
              <el-button @click="timeDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveTime">保存</el-button>
            </div>
          </el-dialog>


          <el-form-item label="营业执照照片" prop="businessLicense">
            <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="handleLicenseSuccess"
                :before-upload="beforeLicenseUpload">
              <img v-if="storeInfo.businessLicense" :src="storeInfo.businessLicense" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>

          <div width="900px">
            <el-button type="text">门店地址:</el-button>
            <!-- 下拉框 -->
            <el-select
                v-model="selectedAddress"
                placeholder="请选择地址"
                style="margin-bottom: 15px; width: 100%"
                >
              <!-- 可在此处动态添加地址选项 -->
              <el-option
                  v-for="(address,index) in addressList"
                  :key="address.id"
                  :value="address.id"
                  :label="address.addressData"
              >
              </el-option>
            </el-select>
            <el-button type="success" @click="newAddress">新增地址</el-button>
          </div>

          <!-- 地址选择对话框 -->
          <el-dialog
              title="选择门店地址"
              v-model="addressDialogVisible"
              width="900px"
              :close-on-click-modal="false"
          >
            <div class="address-select">
              <!-- 省份选择 -->
              <el-select
                  v-model="tempAddress.province"
                  placeholder="请选择省份"
                  @change="handleProvinceChange"
                  style="margin-bottom: 15px; width: 100%"
              >
                <el-option
                    v-for="item in provinces"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>

              <!-- 城市选择 -->
              <el-select
                  v-model="tempAddress.city"
                  placeholder="请选择城市"
                  @change="handleCityChange"
                  style="margin-bottom: 15px; width: 100%"
                  :disabled="!tempAddress.province"
              >
                <el-option
                    v-for="item in cities"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>

              <!-- 区/县选择 -->
              <el-select
                  v-model="tempAddress.area"
                  placeholder="请选择区/县"
                  style="margin-bottom: 15px; width: 100%"
                  :disabled="!tempAddress.city"
              >
                <el-option
                    v-for="item in areas"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>

              <!-- 详细地址输入 -->
              <el-form-item label="街道地址">
                <el-input
                    v-model="tempAddress.street"
                    placeholder="请输入详细街道地址"
                    style="width: 200px"
                />
              </el-form-item>
              <el-form-item label="默认地址">
                <el-switch v-model="tempAddress.isDefault" active-text="是" inactive-text="否" />
              </el-form-item>
            </div>

            <!-- 对话框底部按钮 -->
            <div slot="footer" class="dialog-footer">
              <el-button @click="addressDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveAddress">保存</el-button>
            </div>
          </el-dialog>

          <el-form-item>
            <el-button @click="resetInfoForm">取消</el-button>
            <el-button type="primary" @click="submitInfoForm">确定</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane :label="props.storeId?'编辑门店照片':'新增门店照片'" name="photos">
        <div class="photos-container">
          <div class="photo-item">
            <div class="photo-label">门头照片</div>
            <el-upload
                class="photo-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="(res, file) => handlePhotoSuccess(res, file, 'shopFront')"
                :before-upload="beforePhotoUpload">
              <img v-if="storeInfo.shopFront" :src="storeInfo.shopFront" class="photo" />
              <el-icon v-else class="photo-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </div>

          <div class="photo-item">
            <div class="photo-label">环境照片</div>
            <el-upload
                class="photo-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="(res, file) => handlePhotoSuccess(res, file, 'environment')"
                :before-upload="beforePhotoUpload">
              <img v-if="storeInfo.environment" :src="storeInfo.environment" class="photo" />
              <el-icon v-else class="photo-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </div>

          <div class="photo-item">
            <div class="photo-label">工具设备照片</div>
            <el-upload
                class="photo-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="(res, file) => handlePhotoSuccess(res, file, 'equipment')"
                :before-upload="beforePhotoUpload">
              <img v-if="storeInfo.equipment" :src="storeInfo.equipment" class="photo" />
              <el-icon v-else class="photo-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </div>

          <div class="photo-item">
            <div class="photo-label">工作车间照片</div>
            <el-upload
                class="photo-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="(res, file) => handlePhotoSuccess(res, file, 'workshop')"
                :before-upload="beforePhotoUpload">
              <img v-if="storeInfo.workshop" :src="storeInfo.workshop" class="photo" />
              <el-icon v-else class="photo-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </div>

          <div class="photo-item">
            <div class="photo-label">团队建设照片</div>
            <el-upload
                class="photo-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="(res, file) => handlePhotoSuccess(res, file, 'team')"
                :before-upload="beforePhotoUpload">
              <img v-if="storeInfo.team" :src="storeInfo.team" class="photo" />
              <el-icon v-else class="photo-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </div>
        </div>

        <div class="photo-actions">
          <el-button @click="cancelEditPhotos">取消</el-button>
          <el-button type="primary" @click="saveEditPhotos">确定</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import axios from "axios";
import {ElMessage} from "element-plus";
import { cloneDeep } from 'lodash';
const router = useRouter()

// 当前激活的标签页
const activeTab = ref('info')

// 表单引用
const infoFormRef = ref(null)


// 定义props
const props = defineProps({
  storeId: {
    type: Number, // 或Number（需转换）
    required: false
  }
})

//地址信息
//获取地址信息
const addressList=ref([]);
const selectedAddress=ref(null)
const initAddress=(storeId)=>{
  axios.get(`/carcenter-service-store/store-address/getStoreAddressListByStoreId/${storeId}`).then(resp=>{
    addressList.value=resp.data.data;
    addressList.value.forEach((item)=>{
      if (item.isDefault==1){
        selectedAddress.value=item.id;
      }
    })
  })
}
const addressDialogVisible=ref(false);

const tempAddress=ref({
  "province":null,
  "city":null,
  "area":null,
  "street":'',
  "isDefault":false,
  "storeId":null,
});

const tempAddressId=ref(null);
const saveAddress = async () => {
  // 修复 isDefault 赋值逻辑
  tempAddress.value.isDefault = tempAddress.value.isDefault ? 1 : 0;

  if (props.storeId) {
    tempAddress.value.storeId = props.storeId;
  }

  // 手动提取需要的字段，避免发送整个响应式对象
  const addressModel = {
    isDefault: tempAddress.value.isDefault,
    storeId: tempAddress.value.storeId,
    province: tempAddress.value.province,
    city: tempAddress.value.city,
    area: tempAddress.value.area,
    street: tempAddress.value.street
    // 其他需要的字段...
  };

  try {
    const resp = await axios.post(
        `/carcenter-service-store/store-address/newAddress`,
        addressModel
    );
    const newCreatedAddress = resp.data.data;

    if (props.storeId) {
      initAddress(props.storeId);
    } else {
      tempAddressId.value = newCreatedAddress.id;
      selectedAddress.value = newCreatedAddress.province + newCreatedAddress.city + newCreatedAddress.area + newCreatedAddress.street;
    }

    addressDialogVisible.value = false;
  } catch (error) {
    console.error('保存地址失败:', error);
    // 可以添加错误提示
  }
};

const newAddress=()=>{
  // 重置 tempAddress 为初始对象结构（而非 null）
  tempAddress.value = {
    province: null,
    city: null,
    area: null,
    street: '',
    isDefault: false, // 恢复为布尔值（与初始值一致）
    storeId: props.storeId || null, // 保留 storeId（如果有）
  };
  addressDialogVisible.value=true;
}


// 门店信息
const storeInfo = reactive({
  "id": 1,
  "storeName": "极速汽车服务中心",
  "storeType": "加盟店",
  "servicePhone": "010-12345678",
  "businessHours": "09:00-18:00",
  "businessStatus": "营业中",
  "businessLicense": "110105123456789",
  "stationCount": 10,
  "managerId": 1,
  "businessHoursPeriod ":[]

})

//门店时间
const newTime=()=>{
  timeDialogVisible.value=true;
}
const timeDialogVisible=ref(false);
const saveTime=()=>{
  storeInfo.businessHours =storeInfo.businessHoursPeriod[0]+"-"+storeInfo.businessHoursPeriod[1];
  timeDialogVisible.value=false;
}


// 表单验证规则
const rules = reactive({
  selectedAddress: [ // 修改为selectedAddress
    { required: true, message: '请选择门店地址', trigger: 'change' }
  ],
  storeName:[
    { required: true, message: '请输入门店名称', trigger: 'blur' }
  ],
  storeType: [
    { required: true, message: '请选择门店类型', trigger: 'change' }
  ],
  servicePhone: [
    { required: true, message: '请输入门店电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  businessHours: [
    { required: true, message: '请选择营业时间', trigger: 'change' }
  ],
  businessStatus: [
    { required: true, message: '请输入营业状态', trigger: 'blur' }
  ],
  managerId: [
    { required: true, message: '请输入店长ID', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请选择省份', trigger: 'change' }
  ],
  city: [
    { required: true, message: '请选择城市', trigger: 'change' }
  ],
  area: [
    { required: true, message: '请选择区/县', trigger: 'change' }
  ],
  street: [
    { required: true, message: '请输入街道信息', trigger: 'blur' }
  ]
})

// 地区数据
const provinces = ref([])
const cities = ref([])
const areas = ref([])


// 省份变更
const handleProvinceChange = () => {
  // 根据省份获取城市列表
  axios.get(`/carcenter-service-store/store-china/getCities/${tempAddress.value.province}`).then(response => {
    cities.value = response.data.data;
  }).catch(error => {
    ElMessage.error(error.response.data)
  })
}

// 城市变更
const areaDisabled=ref(false);
const handleCityChange = () => {
  // 根据城市获取区县列表
  axios.get(`/carcenter-service-store/store-china/getAreas/${tempAddress.value.city}`).then(response => {
    areas.value = response.data.data;
    if (areas.value.length === 0) {
      areaDisabled.value = true;
      tempAddress.value.area = null;
    }else {
      areaDisabled.value = false;
    }
  }).catch(error => {
    ElMessage.error(error.response.data)
  })
}


const getProvinces = () => {
  axios.get(`/carcenter-service-store/store-china/getProvinces`).then(resp => {
    provinces.value = resp.data.data;
  })
}

// 页面加载时初始化数据
onMounted(() => {
  // 检查是否为编辑模式
  if ( props.storeId) {
    // 模拟从API获取门店数据

    fetchStoreData(props.storeId);
    initAddress(props.storeId);
  } else {
    // 新增模式，初始化表单
    initNewStoreForm()
  }
  getProvinces();
})

// 初始化新增门店表单
const initNewStoreForm = () => {
  storeInfo.id=null;
  storeInfo.storeName='';
  storeInfo.storeType='';
  storeInfo.stationCount=null;
  storeInfo.managerId=null;
  storeInfo.businessHours='';
  storeInfo.servicePhone='';
  storeInfo.businessStatus='';
  storeInfo.businessLicense='';
}

// 获取门店数据
const fetchStoreData = (storeId) => {
  axios.get(`/carcenter-service-store/store-info/getStoreById/${storeId}`).then(resp => {
    Object.assign(storeInfo, resp.data.data);

  })
}



// 处理营业执照上传成功
const handleLicenseSuccess = (response, file) => {
  storeInfo.businessLicense = URL.createObjectURL(file.raw)
  ElMessage.success('营业执照上传成功')
}

// 处理照片上传成功
const handlePhotoSuccess = (response, file, photoType) => {
  storeInfo[photoType] = URL.createObjectURL(file.raw)
  ElMessage.success('照片上传成功')
}

// 照片上传前校验
const beforePhotoUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
  }

  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }

  return isJPG && isLt2M
}

// 营业执照上传前校验
const beforeLicenseUpload = (file) => {
  return beforePhotoUpload(file)
}


// 提交门店信息表单
const submitInfoForm = async () => {
  try {
    // 验证表单
    const valid = await new Promise(resolve => {
      infoFormRef.value.validate(resolve);
    });

    if (!valid) {
      ElMessage.error('表单验证失败，请检查必填项');
      return;
    }


    if (props.storeId) {
      // 编辑门店信息
      axios.put(
          `/carcenter-service-store/store-info/editStore`,
          storeInfo
      ).then(response => {
        ElMessage.success(response.data.message);
      })
    } else {
      // 新增门店信息
      let resp = await axios.post(
          `/carcenter-service-store/store-info/newStore`,
          storeInfo
      );

      await axios.put(
          `/carcenter-service-store/store-address/addAddressStoreId/${tempAddressId.value}/${resp.data.data.id}`
      ).then(response => {
        ElMessage.success(response.data.message);
      });
      tempAddressId.value = null;
    }

    // 返回上一页
    router.back();
  } catch (error) {
    // 错误处理
    console.error('提交表单失败:', error);
    ElMessage.error('操作失败，请稍后重试');
  }
};

// 重置门店信息表单
const resetInfoForm = () => {
  if (props.storeId) {
    // 编辑模式，重新加载数据
    fetchStoreData(props.storeId)
  } else {
    // 新增模式，清空表单
    infoFormRef.value.resetFields()
    initNewStoreForm()
  }
  router.go(-1);
}

// 保存编辑的照片
const saveEditPhotos = () => {
  // 模拟API请求
  setTimeout(() => {
    // 实际项目中应该发送数据到API

    // 显示成功消息
    ElMessage({
      type: 'success',
      message: '门店照片更新成功'
    })

    // 返回上一页
    router.back()
  }, 300)
}

// 取消编辑照片
const cancelEditPhotos = () => {
  if (props.storeId) {
    // 编辑模式，重新加载数据
    fetchStoreData(props.storeId)
  } else {
    // 新增模式，清空照片
    storeInfo.shopFront = ''
    storeInfo.environment = ''
    storeInfo.equipment = ''
    storeInfo.workshop = ''
    storeInfo.team = ''
  }
  router.go(-1);
}

// 标签页切换事件
const handleTabClick = (tab) => {
  activeTab.value = tab.name
}
</script>

<style scoped>
.store-edit-new-container {
  padding: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.photos-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.photo-item {
  display: flex;
  flex-direction: column;
}

.photo-label {
  margin-bottom: 10px;
  font-weight: bold;
}

.photo-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.photo-uploader .el-upload:hover {
  border-color: #409eff;
}

.photo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.photo {
  max-width: 100%;
  max-height: 200px;
  display: block;
}

.photo-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.address-select {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}
</style>
